<?php
namespace Modules\Social\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Core\Http\Controllers\BaseController;
use Modules\Core\Models\User;
use Modules\Social\Models\UserSocial;

class OAuthController extends BaseController
{
    protected $socialite;

    /**
     * OAuthController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->middleware(function ($request, $next) {
            $this->socialite = UserSocial::init();
            return $next($request);
        });
    }

    /**
     * @param $driver
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function redirectToProvider($driver, Request $request)
    {
        if($_redirect = $request->get('redirect')) {
            return $this->socialite->driver($driver)->withRedirectUrl($_redirect)->redirect();
        }else{
            return $this->socialite->driver($driver)->redirect();
        }
    }


    /**
     * @param $driver
     * @param $oid
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handleProviderCallback($driver, Request $request)
    {
        $user =  $this->socialite->driver($driver)->user();
        UserSocial::login($driver, $user->id, $user);

        return redirect('/');
    }
}
